package com.terren.webdig.common.util;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Json Util
 * 
 * @author Administrator
 *
 */
public class JsonUtil {

	/**
	 * 分页
	 * 
	 * @param data
	 * @param recordsTotal
	 * @return
	 */
	public static String pagingJson(List<?> data) {
		return pagingJson(data, data.size(), null, null);
	}

	/**
	 * 得到对象的JSON
	 * 
	 * @param obj
	 * @return
	 */
	public static String toJSONString(Object obj) {
		return JSON.toJSONString(obj);
	}

	/**
	 * amazeui分页
	 * 
	 * @param data
	 * @param recordsTotal
	 * @param draw
	 * @return
	 */
	public static String pagingJson(List<?> data, Integer recordsTotal, Integer draw) {

		return pagingJson(data, recordsTotal, recordsTotal, draw);
	}

	/**
	 * 
	 * @param data
	 * @param recordsTotal
	 * @param recordsFiltered
	 * @param draw
	 * @return
	 */
	public static String pagingJson(List<?> data, Integer recordsTotal, Integer recordsFiltered, Integer draw) {
		AmazeuiData store = new AmazeuiData();
		store.setData(data);
		store.setRecordsTotal(recordsTotal);
		store.setDraw(draw);
		store.setRecordsFiltered(recordsFiltered);
		String json = JSON.toJSONString(store);
		return json;
	}

	/**
	 * 返回ajax执行结果
	 * 
	 * @param isSuccess
	 * @param msg
	 * @return
	 */
	public static String messageJson(boolean isSuccess, String msg) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", isSuccess);
		resultMap.put("msg", msg);
		String json = JSON.toJSONString(resultMap);
		return json;
	}

	/**
	 * 获取json数据中某个节点下的json
	 * 
	 * @param data
	 * @param jsonNode
	 * @return
	 */
	public static String filterJson(String data, String jsonNode) {
		String filterData = null;
		Gson gson = new Gson();
		Type type = new TypeToken<Map<String, Object>>() {
		}.getType();
		Map<String, Object> myMap = gson.fromJson(data, type);

		filterData = gson.toJson(myMap.get(jsonNode));
		return filterData;
	}
}

class AmazeuiData {
	private Integer recordsFiltered;
	private Integer draw;
	private Integer recordsTotal;
	private List<?> data;

	public Integer getRecordsFiltered() {
		return recordsFiltered;
	}

	public void setRecordsFiltered(Integer recordsFiltered) {
		this.recordsFiltered = recordsFiltered;
	}

	public Integer getDraw() {
		return draw;
	}

	public void setDraw(Integer draw) {
		this.draw = draw;
	}

	public Integer getRecordsTotal() {
		return recordsTotal;
	}

	public void setRecordsTotal(Integer recordsTotal) {
		this.recordsTotal = recordsTotal;
	}

	public List<?> getData() {
		return data;
	}

	public void setData(List<?> data) {
		this.data = data;
	}
}
